package game.action;

import game.Client;

import java.util.Random;

/**
 * tick驱动定时执行某项任务(基类)
 */
public abstract class ActionBase {

    private String classSimpleName;//子类名
    private int tickTimeBegin;//随机范围(毫秒)
    private int tickTimeEnd;//随机范围(毫秒)
    private long randomTickTime;//tick间隙，每次重新随机
    private long lastActionTime;//最近一次执行成功的时间戳

    public ActionBase(int tickTimeBegin, int tickTimeEnd) {
        this.classSimpleName = this.getClass().getSimpleName();
        this.tickTimeBegin = Math.max(1, tickTimeBegin);
        this.tickTimeEnd = Math.max(Math.max(1, tickTimeEnd), this.tickTimeBegin);
        this.randomTickTime = randomTickTime();
        this.lastActionTime = System.currentTimeMillis();
    }

    /**
     * 时间周期tick
     */
    public void run(long now, Client client) {
        if (!this.classSimpleName.equals(ReconnectAction.class.getSimpleName())) {
            if (!client.isLoginOK()) {
                return;//没登陆前其他行为不可执行
            }
        }
        if (now - this.lastActionTime < this.randomTickTime) {
            return;
        }
        this.lastActionTime = System.currentTimeMillis();
        this.randomTickTime = randomTickTime();//每次都重新随机一个delay时间
        action(client);
    }

    private long randomTickTime() {
        if (tickTimeEnd == tickTimeBegin) {
            return tickTimeBegin;
        }
        Random random = new Random();
        return random.nextInt(tickTimeEnd) % (tickTimeEnd - tickTimeBegin + 1) + tickTimeBegin;
    }

    /**
     * 具体行为实现
     */
    public abstract void action(Client client);
}
